<?php
/**
 * Created by PhpStorm.
 * User: sen
 * Date: 16/7/13
 * Time: 下午4:18
 */
namespace app\controllers;
use yii\web\Controller;
use app\models\Proxy;
use app\models\ProxyApply;
use app\models\User;

class AgentController extends Controller{


    public function init(){
        $this->enableCsrfValidation = false;
        if(!\Yii::$app->user->id){
            $url = \Yii::$app->request->getPathInfo();
            return $this->redirect('../login/index?url='.$url);
        }
        $userId = \Yii::$app->user->id;
        $user = new User();
        $admin = $user->findIdentity($userId);
        if($admin['type']==1 or $admin['type']==0){
            return $this->redirect('../login/logout');
        }
    }

//    代理申请界面
    public function actionCheckAgent(){

        $view = \Yii::$app->view;
        $view->params['menuitemid'] = 51;
        return $this -> render('newcheckagent');
    }

//    代理管理界面
    public function actionAgentList(){

        $view = \Yii::$app->view;
        $view->params['menuitemid'] = 52;
        return $this -> render('newagentlist');

    }

    //获取代理申请列表数据
    public function actionCheckAgentTableData(){

        //获取相应字段
        $request = \Yii::$app->request;
        $offset = $request->get('offset');
        $limit = $request->get('limit');
        $search = $request->get('search');
        $leader_id = \Yii::$app->user->id;

        $model = new ProxyApply();
        $rs = $model->getCheckAgentTableData($limit,$offset,$search,$leader_id);
        echo json_encode($rs);

    }

    //获取代理列表数据
    public function actionAgentListTableData(){

        //获取相应字段
        $request = \Yii::$app->request;
        $offset = $request->get('offset');
        $limit = $request->get('limit');
        $search = $request->get('search');
        $leader_id = \Yii::$app->user->id;

        $model = new Proxy();
        $rs = $model->getAgentListTableData($limit,$offset,$search,$leader_id);
        echo json_encode($rs);

    }

    //代理申请审批
    public function actionCheckAgentOperate(){

        //获取相应字段
        $request = \Yii::$app->request;
        $apply_id = $request->get('apply_id');
        $status = $request->get('status');

        $model = ProxyApply::findOne(['apply_id'=>$apply_id]);
        $model->status = $status;
        $rs=$model->save();  // 等同于 $model->update();

        if($status==1){
            $apply =  ProxyApply::getcurrent($apply_id);

            \Yii::$app->db->createCommand()->insert('hcps_proxy', [

                'user_id' => $apply['user_id'],
                'leader_id' => $apply['leader_id'],
                'del_flag' => 1,
                'create_time' => date('Y-m-d h:i:s',time()),
                'content' => $apply['content'],
                'mobile' => $apply['mobile'],

            ])->execute();

            User::updateAll(['type' => '1'],['user_id' => [$apply['user_id']]]);
        }else{
            ProxyApply::updateAll(['status'=>'2'],['apply_id' => $apply_id]);
        }

        echo json_encode($rs);

    }



    // 撤销代理方法
    public function actionRemovegrate(){

        $request = \Yii::$app->request;
        $currentId = $request->get('user_id');
        Proxy::updateAll(['del_flag' => '0'],['user_id' => $currentId]);//删除改代理
        User::updateAll(['type' => '0'],['user_id' => $currentId]);
        //删除该代理下级代理
        $this->actionRemoveall($currentId);
        //删除该代理及下级代理的佣金关系
        $this->removeAllBrokerageRelations($currentId);

        // ajax 要返回一个正确格式的json 不然不走success方法
        return json_encode(['success' => true]);
    }


    public function actionRemoveall($leaderid){

        $statusArray = Proxy::find() -> where(['leader_id' => $leaderid, 'del_flag' => 1]) -> asArray() -> all();
        $num = count($statusArray);

        for($i=0;$i<$num;$i++){

            Proxy::updateAll(['del_flag' => '0'],['user_id' => $statusArray[$i]['user_id']]);
            User::updateAll(['type' => '0'],['user_id' => [$statusArray[$i]['user_id']]]);

            $this -> actionRemoveall($statusArray[$i]['user_id']);

        }
    }

    private function removeAllBrokerageRelations($agentId) {
        $sql = \Yii::$app->db
            ->createCommand(
                'UPDATE distribution.hcps_brokerage_relationship SET del_flag = 0 WHERE customer_user_id IN
                (SELECT * FROM 
                (SELECT DISTINCT customer_user_id FROM distribution.hcps_brokerage_relationship WHERE agent_user_id = :agent_id AND del_flag = 1) temp
                )')
            ->bindValue(':agent_id', $agentId)
            ->execute();
    }
}